﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Threading;
using System.Reflection; // 引用这个才能使用Missing字段
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Xml;
using System.Web;
using System.Runtime.InteropServices;
using CCWin;

namespace weiqijiance
{
    public partial class TESTAP : Form
    {
        public mainform m_mainform;
        public string sdetid;
        /// <summary>
        /// 结果变量
        /// </summary>
        public string sbufuhexiang;
        public string jylsh;
        public string jyjgbh;
        public string jcxdh;
        public string jycs;
        public string jyxm;
        public string hpzl;
        public string hphm;
        public string clsbdh;

        public string dpjcjyy;
        public string dpjyysfzh;

        public bool bsdsmjyy = false;
        public Thread t1;
        public Thread t2;
        public string xianshineirong;
        public string businessId;
        public string sshebei = "地沟";
        public string revert = "";

        // /声明INI文件的写操作函数 WritePrivateProfileString()
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        //声明INI文件的读操作函数 GetPrivateProfileString()
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        private string sPath = null;


        public 控制流程.flowcrtl flowbass = new 控制流程.flowcrtl();
        private SerialPort comAP = new SerialPort();//地沟串口
        public TESTAP(int Width, int Height)
        {

                InitializeComponent();
                panel_Width = Width;
                panel_Height = Height;
                //this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
                x = this.Width;
                y = this.Height;
                setTag(this);
                xinxixianshi.Text = "底盘检查";
                sbufuhexiang = "";


        }
        bool bzjddzj = false;
        public void initcom()
        {
            iniclass objini = new iniclass();
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\安综检仪表配置.ini";
            string path1 = string.Format(@"{0}", path);
            objini.Ini(path1);
            showtime = objini.ReadValue("地沟", "地沟显示检测时间").Trim();
            APzhijiekaishi = objini.ReadValue("地沟", "地沟不需扫码直接开始").Trim().Contains("是") ? true : false;
            bdpjxylx = objini.ReadValue("地沟", "增加底盘间隙仪录像").Trim().Contains("是") ? true : false;
            string sSetCom = objini.ReadValue("地沟", "扫描枪串口设置").Trim();
            bsdsmjyy = objini.ReadValue("地沟", "扫描检验员").Trim().Contains("是") ? true : false;
            bzjddzj = objini.ReadValue("地沟", "只检单独综检").Trim().Contains("是") ? true : false;
            if (sSetCom != "")
            {
                m_mainform.openCOM(sSetCom, comAP);
                comAP.ReadTimeout = 500;
                //comAP.ReceivedBytesThreshold = 10;//达到50字节以后才开始触发串口
                comAP.DataReceived += comAP_DataReceived;
            }
        }
        string stiaoma = "";
        void comAP_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (comAP.IsOpen)
            {
                Thread.Sleep(10);
                int n = comAP.BytesToRead;//
                byte[] buf1 = new byte[n];//声明一个临时数组存储当前来的串口数据  
                byte[] buf = new byte[n];
                comAP.Read(buf1, 0, n);

                string scom = "";
                scom = System.Text.Encoding.Default.GetString(buf1);
                stiaoma = scom;
            }

        }
        public void start()
        {
            bianliangchushihua();
            t1 = new Thread(new ThreadStart(Thread1));
            t2 = new Thread(new ThreadStart(Thread2));
            t2.Priority = ThreadPriority.Lowest;
            t2.Start();
            dpjcjyy = "1";//车辆底盘检验员
            dpjyysfzh = "1";//车辆底盘检验员（身份证号）

            //if (m_mainform.szdksjc.Contains("是"))
            {
                t1 = new Thread(new ThreadStart(Thread1));
                t1.Priority = ThreadPriority.BelowNormal;
                t1.Start();
            }
        }
        /// <summary>
        /// 变量初始化
        /// </summary>
        public void bianliangchushihua()
        {
            sbufuhexiang = "";
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\车辆信息.ini";
            string path1 = string.Format(@"{0}", path);
            Ini(path1);

        }
        #region 控件大小随窗体大小等比例缩放
        private float x;//定义当前窗体的宽度
        private float y;//定义当前窗体的高度
        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    setTag(con);
                }
            }
        }
        private void setControls(float newx, float newy, Control cons)
        {
            if (newy <= 0)
            {
                newy = 1;
            }
            //遍历窗体中的控件，重新设置控件的值
            foreach (Control con in cons.Controls)
            {
                //获取控件的Tag属性值，并分割后存储字符串数组
                if (con.Tag != null)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
                    //根据窗体缩放的比例确定控件的值
                    con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx);//宽度
                    con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy);//高度
                    con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx);//左边距
                    con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy);//顶边距
                    Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小
                    if (currentSize<0)
                    {
                        currentSize = 8;
                    }
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
        }
        #endregion

        //ini文件
        public void Ini(string path)
        {
            this.sPath = path;
        }
        public void Writue(string section, string key, string value)
        {
            // section=配置节，key=键名，value=键值，path=路径
            WritePrivateProfileString(section, key, value, sPath);
        }
        public string ReadValue(string section, string key)
        {
            // 每次从ini中读取多少字节
            System.Text.StringBuilder temp = new System.Text.StringBuilder(255);

            // section=配置节，key=键名，temp=上面，path=路径
            GetPrivateProfileString(section, key, "", temp, 255, sPath);
            return temp.ToString();
        }
        //ini文件


        private delegate void FlushClient();//代理
        private void xianshi()
        {
            if (this.xinxixianshi.InvokeRequired)//等待异步
            {
                FlushClient fc = new FlushClient(xianshi);
                this.Invoke(fc);//通过代理调用刷新方法
            }
            else
            {
                this.xinxixianshi.Text = string.Format(@"{0}", xianshineirong);
            }
        }

       

       
        protected void thisclose()
        {

            this.Invoke(new Action(this.Close));  //使用委托关闭该窗体
        }
        public string showtime;
        public bool bdpjxylx;
        public void StratTest()
        {
            flowbass.objcarclass.tongdao1 = flowbass.iaptongdao.ToString();
            flowbass.objcarclass.tongdao2 = flowbass.idpjxytongdao.ToString();
            flowbass.objcarclass.bdpjxylx = bdpjxylx;//是否启用底盘间隙仪
            if (bdpjxylx && (flowbass.sPclass.Contains("大型") || flowbass.sPclass.Contains("教练") || (flowbass.sPclass.Contains("警")&&flowbass.sCllx.Contains("大"))))
            {
                flowbass.objcarclass.bdpjxz = true;
            }
            else
            {
                flowbass.objcarclass.bdpjxz = false;
            }

            APbegin = false;
            APend = false;
            if (!flowbass.bJCDG)
            {
                xianshineirong = string.Format(@"底盘免检");
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                return;
            }

            //扫描检验员
            string sid = "001";
            
            while (true)
            {
                if (!bsdsmjyy)
                {
                    break;
                }
                Thread.Sleep(10);
                xianshineirong = string.Format(@"请扫检验员编号");
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                if (stiaoma.Contains("A"))
                {
                    sid = stiaoma.Replace("A","").Trim();
                    break;
                }
            }

            xianshineirong = string.Format(@"底盘检查");
            xianshi();
            stiaoma = "";
            flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
            while(true)
            {
                Thread.Sleep(10);
                if (stiaoma.Contains("9995") || APbegin || APzhijiekaishi)
                {
                    flowbass.UpdateLoginRecord(DateTime.Now.ToString(), "底盘检验开始", flowbass.sDetectID);

                    flowbass.RecordProcessTime(int.Parse(flowbass.sDetectID), flowbass.sPlate, flowbass.sPclass, "ChassisParts", DateTime.Now, flowbass.iITERAT, "开始");
                    break;
                }
                if (flowbass.IsCancle())
                {
                    return;
                }
            }

            xianshineirong = string.Format(@"底盘检查开始");
            xianshi();
           
            flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);

            stiaoma = "";

            string sbuhege = "";
            bool Dcconlusion = false;
            //测量数据
            DateTime dstart = DateTime.Now;
            var datatime = 0;
            while(true)
            {
                
                if (showtime.Contains("是")&&m_mainform.DateDiff(DateTime.Now, dstart) > 1000)
                {
                    dstart = DateTime.Now;
                    datatime++;
                    xianshineirong = string.Format(@"底盘检查已检{0}秒", datatime);
                    xianshi();
                    flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                }
                Thread.Sleep(10);
                if (flowbass.IsCancle())
                {
                    return;
                }
                if (stiaoma.Contains("9995"))
                {
                    stiaoma = "";
                }
                if (stiaoma.Contains("9999")||APend)
                {
                    if (flowbass.bnj)
                    {
                        flowbass.objajlwbass.sendpic(flowbass.iaptongdao.ToString(), "0323", flowbass.objcarclass);//图片抓拍
                    }
                    xianshineirong = string.Format(@"底盘检查完成");
                    xianshi();
                    flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                    stiaoma = "";
                    flowbass.UpdateLoginRecord(DateTime.Now.ToString(), "底盘检验结束", flowbass.sDetectID);
                    break;
                }
                else
                {
                    if (flowbass.sjcbz.Contains("38900"))
                    {
                        showbhg38900();
                    }
                    else
                    {
                        showbhg();
                    }
                }
               
                Thread.Sleep(300);
            }
            if ((sbuhege+"").Length<1)
            {
                Dcconlusion = true;
            }
            if (!Dcconlusion)
            {
                flowbass.getbuhge(flowbass.sDetectID, "C1");
            }
            else
            {

                flowbass.sethege(flowbass.sDetectID, "C1");
            }
          
            //检测结束
           

            flowbass.AddData(flowbass.sDetectID, "DET_DCJL", "Detects_SJA", Dcconlusion?1:2);
            flowbass.AddData_Check(flowbass.sDetectID, "DET_DC", "Detects_SJA", sbuhege);
            flowbass.getProcessfinish(flowbass.sDetectID, "C1");
            //检测结束

            //安检数据检测数据上传
            model.安检联网.modelC1 objmodellw = new model.安检联网.modelC1();
            if (flowbass.sjcbz.Contains("38900"))
            {
                objmodellw.rzxxbj = sbuhege.Contains("47") ? "2" : "1";//c测试
                objmodellw.rcdxbj = sbuhege.Contains("48") ? "2" : "1";
                objmodellw.rxsxbj = sbuhege.Contains("49") ? "2" : "1";
                objmodellw.rzdxbj = sbuhege.Contains("50") ? "2" : "1";
                objmodellw.rqtbj = sbuhege.Contains("51") ? "2" : "1";
            }
            else
            {
                objmodellw.rzxxbj = sbuhege.Contains("45") ? "2" : "1";//c测试
                objmodellw.rcdxbj = sbuhege.Contains("46") ? "2" : "1";
                objmodellw.rxsxbj = sbuhege.Contains("47") ? "2" : "1";
                objmodellw.rzdxbj = sbuhege.Contains("48") ? "2" : "1";
                objmodellw.rqtbj = sbuhege.Contains("49") ? "2" : "1";
            }
            objmodellw.ycyjy = "";
            objmodellw.bz = "";
            if (flowbass.sPclass.Contains("挂") || flowbass.sCllx.Substring(0, 1).Contains("B") || flowbass.sCllx.Substring(0, 1).Contains("G"))
            {
                objmodellw.rzxxbj = "0";
                objmodellw.rcdxbj = "0";
            }
            //objmodellw.dpjcjyy = dpjcjyy;
            if (flowbass.getdpjyy(flowbass.sDetectID).Trim().Length > 0)
            {
                dpjcjyy = flowbass.getdpjyy(flowbass.sDetectID);
            }
            else
            {
                dpjcjyy = flowbass.getidname(sid);
            }
            objmodellw.dpjcjyy = dpjcjyy;
            objmodellw.dpjyysfzh = flowbass.getycysfz(dpjcjyy);
            objmodellw.ycy = flowbass.sYCY;
            objmodellw.ycysfzh = flowbass.getycysfz(flowbass.sYCY);
            //数据上传
            if (flowbass.bnj && !bzjddzj)
            {
                revert = flowbass.objajlwbass.write(flowbass.objcarclass, objmodellw);
                if (!(revert.Length > 0 && revert[0].ToString() == "1"))
                {
                    flowbass.LedWrite("联网失败", revert, 1); Thread.Sleep(2000);
                }
            }
            //flowbass.AddData_Check(flowbass.sDetectID, "DET_DPCZY", "Detects_SJA", dpjcjyy);//底盘检验员
            ///
            
            flowbass.RecordProcessTime(int.Parse(flowbass.sDetectID), flowbass.sPlate, flowbass.sPclass, "ChassisParts", DateTime.Now, flowbass.iITERAT, "结束");

            flowbass.Updatejcxhao(flowbass.objcarclass.jcxdh, flowbass.sDetectID);
        }
        void showbhg()
        {
            if (stiaoma.Contains("0045"))//不合格项目
            {
                xianshineirong = string.Format(@"不合格项：{0}", stiaoma);
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                stiaoma = "";
            }
            if (stiaoma.Contains("0046"))
            {
                xianshineirong = string.Format(@"不合格项：{0}", stiaoma);
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                stiaoma = "";
            }
            if (stiaoma.Contains("0047"))
            {
                xianshineirong = string.Format(@"不合格项：{0}", stiaoma);
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                stiaoma = "";
            }
            if (stiaoma.Contains("0048"))
            {
                xianshineirong = string.Format(@"不合格项：{0}", stiaoma);
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                stiaoma = "";
            }
            if (stiaoma.Contains("0049"))
            {
                xianshineirong = string.Format(@"不合格项：{0}", stiaoma);
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                stiaoma = "";
            }
        }
        void showbhg38900()
        {
            if (stiaoma.Contains("0047"))//不合格项目
            {
                xianshineirong = string.Format(@"不合格项：{0}", stiaoma);
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                stiaoma = "";
            }
            if (stiaoma.Contains("0048"))
            {
                xianshineirong = string.Format(@"不合格项：{0}", stiaoma);
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                stiaoma = "";
            }
            if (stiaoma.Contains("0049"))
            {
                xianshineirong = string.Format(@"不合格项：{0}", stiaoma);
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                stiaoma = "";
            }
            if (stiaoma.Contains("0050"))
            {
                xianshineirong = string.Format(@"不合格项：{0}", stiaoma);
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                stiaoma = "";
            }
            if (stiaoma.Contains("0051"))
            {
                xianshineirong = string.Format(@"不合格项：{0}", stiaoma);
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                stiaoma = "";
            }
        }
        public void Thread1()
        {
            try
            {

                StratTest();
                if (flowbass.LastProcessnew(int.Parse(flowbass.sDetectID)) && !flowbass.ifinish)
                {
                    flowbass.LedWrite("正在发送", "联网总结束", 1);
                    string slianwangfanhui = flowbass.objajlwbass.sendAJend(flowbass.jylsh, false, flowbass.bzj);
                    if (!(slianwangfanhui.Length > 0 && slianwangfanhui[0].ToString() == "1"))
                    {
                        flowbass.LedWrite("联网失败", slianwangfanhui, 1);
                    }
                    else
                    {
                        flowbass.LedWrite("发送完成", "", 1);
                        flowbass.UpdateLoginRecord(DateTime.Now.ToString(), "检测线完成", flowbass.sDetectID);
                    }
                    Thread.Sleep(2000);
                }
                if (flowbass.LastProcessnewzj(int.Parse(flowbass.sDetectID)) && (flowbass.bzj || flowbass.bsj))
                {
                    xianshineirong = "检测线完成";
                    flowbass.UpdateLoginRecord(DateTime.Now.ToString(), "检测线完成", flowbass.sDetectID);
                    flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                    flowbass.sethegezj(flowbass.sDetectID);
                    Thread.Sleep(2000);
                }
                flowbass.LedWrite(flowbass.sgongwei, "", 1);
                xianshineirong = flowbass.sgongwei;
                xianshi();
                end();

                //t1.Abort();
                //t1.DisableComObjectEagerCleanup();
            }
            catch (Exception ex)
            {
                if (!(ex is System.Threading.ThreadAbortException))
                {
                    flowbass.LedWrite(flowbass.sPlate, "异常,停止检测", 1);

                    //错误日记 记录到当天日期下目录中
                    m_mainform.baocunriji("地沟", ex.Message.ToString());
                    m_mainform.SaveErrorLog("地沟检测流程", ex.Message.ToString());

                }
            }
           
        }
        public void Thread2()
        {
           


        }
        public int panel_Width;
        public int panel_Height;   
        private void TESTAP_Resize(object sender, EventArgs e)
        {
            //float newx = (panel_Width) / x;
            //float newy = (panel_Height) / y;
            //setControls(newx, newy, this);
        }

        private void TESTAP_Load(object sender, EventArgs e)
        {
           
        }

       

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (flowbass.izhuangtai == 2)
            {

                m_mainform.objyibiaobass.select(flowbass.sshebei);
                m_mainform.bpanelshow = true;
                m_mainform.showpanel();
                flowbass.izhuangtai = 1;
               

                flowbass.IsReadyForStart();
                bianliangchushihua();
                t1 = new Thread(new ThreadStart(Thread1));
                t1.Start();
                //this.ShowDialog();
            }
        }
        public void timerstart()
        {
            timer1.Enabled = true;
        }
        public void end()
        {
            flowbass.izhuangtai = 0;
            flowbass.sendend("E", flowbass.sDetectID);
            //closeform();
        }
        private void closeform()
        {
            if (this.InvokeRequired)//等待异步
            {
                FlushClient fc = new FlushClient(closeform);
                this.Invoke(fc);//通过代理调用刷新方法
            }
            else
            {
                this.Dispose();
                this.Close();
            }
        }

        private void 仪表设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            工位配置.APsetting obj = new 工位配置.APsetting();
            obj.ShowDialog();
        }
        public bool APbegin;
        public bool APzhijiekaishi;
       
        public bool APend;
       

        private void but_alone_Click(object sender, EventArgs e)
        {
            start();
        }

        private void but_strat_Click(object sender, EventArgs e)
        {
            APbegin = true;
        }

        private void but_end_Click(object sender, EventArgs e)
        {
            APend = true;
        }

        private void 显示控件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowControls(true);
            ShowButtons(true);
        }
        public void ShowControls(bool flag)
        {
            but_alone.Visible = flag;
            but_strat.Visible = flag;
            but_end.Visible = flag;
        }
        public void ShowButtons(bool flag)
        {
            but_alone.Visible = flag;
            but_strat.Visible = flag;
            but_end.Visible = flag;
            
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            start();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            APbegin = true;
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            APend = true;
        }

        private void TESTAP_Shown(object sender, EventArgs e)
        {
            try
            {
                float newx = (this.Width) / x;
                float newy = (this.Height) / y;
                setControls(newx, newy, this);
                ShowButtons(false);
                this.BackgroundImage = Image.FromFile(@"./ico/底盘背景.jpg");//
                this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            }
            catch (Exception ex)
            {
                m_mainform.baocunriji("底盘Load失败", ex.Message.ToString());
                m_mainform.SaveErrorLog("底盘Load失败", ex.Message.ToString());
            }
        }

    }
}
